﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Handles login and logout logic
/// </summary>
public static class LoginHandler
{
    //Session key name
    private static readonly string m_loggedInSessionName = "loggedIn";    
    //RequestQuery name
    private static string m_logoutQueryName = "logout";
    //What m_logoutQueryName should be to logout
    private static string m_logoutValue = "true";
    //Path to the login credentials file
    private static string m_loginFile = Paths.serverBase + "../SecretStuff/login.txt";

    private static bool m_intilized = false;
    
    public static string LogoutQueryName
    {
        get { return m_logoutQueryName; }
        private set { m_logoutQueryName = value; }
    }
    public static string LogoutValue
    {
        get { return m_logoutValue; }
        private set { m_logoutValue = value; }
    }

    public static void SetPaths()
    {
        if (!m_intilized)
        {
            m_loginFile = Paths.serverBase + "../SecretStuff/login.txt";
            m_intilized = true;            
        }        
    }
    
    public static bool FileExists()
    {
        return File.Exists(m_loginFile);
    }

    /// <summary>
    /// Tries to login with given username & password
    /// </summary>
    /// <param name="a_username">username, none case-sensative</param>
    /// <param name="a_passwordHash">a hashed password to compare</param>
    /// <param name="a_session">The Server session, it will write to it if succesful at logging in</param>
    /// <returns></returns>
    public static bool TryToLogin(string a_username, string a_passwordHash, System.Web.SessionState.HttpSessionState a_session)
    {
        string f_user, f_password;

        try
        {
            using (StreamReader sr = new StreamReader(m_loginFile))
            {
                char[] f_delimiter = new char[] { ':' };

                string f_line = sr.ReadLine();
                f_user = f_line.Split(f_delimiter, 2)[1];

                f_line = sr.ReadLine();
                f_password = f_line.Split(f_delimiter, 2)[1];

                sr.Close();
            }               

            //Compare username & password
            if ( String.Equals(a_username ,f_user, StringComparison.OrdinalIgnoreCase) && a_passwordHash == f_password)
            {
                a_session.Add(m_loggedInSessionName, true);

                return true;
            }            
        }
        catch
        {
            a_session.Remove(m_loggedInSessionName);
        }

        return false;
        
    }

    //Check if user is logged in    
    public static bool IsLoggedIn(System.Web.SessionState.HttpSessionState a_session)
    {
        if (a_session == null)
        {
            return false;
        }
        
        bool? f_loggedIn = a_session[m_loggedInSessionName] as bool?;

        return f_loggedIn.HasValue && f_loggedIn.Value;       
    }
    //Logs the user out
    public static bool Logout(System.Web.SessionState.HttpSessionState a_session)
    {
        if (a_session != null)
        {
            bool? f_loggedIn = a_session[m_loggedInSessionName] as bool?;

            if (f_loggedIn.HasValue)
            {
                a_session.Remove(m_loggedInSessionName);
                return true;
            }
        }

        return false;
    }

    //Adds Logout url part to an url
    public static string GetLogoutURL()
    {
        return Paths.admin_logout;// + "?" + m_logoutQueryName + "=" + m_logoutValue;
    }

    //Writes to the credentials file username & password
    public static bool CreateLoginCredentials(string a_username, string a_passwordHash)
    {
        bool f_succeeded = false;
        
        if (!File.Exists(m_loginFile) )
        {            
            try
            {             
                
                using (StreamWriter sw = new StreamWriter(m_loginFile, false, System.Text.Encoding.UTF8 ))
                {
                    sw.WriteLine("user:" + a_username);
                    sw.WriteLine("password:" + a_passwordHash);

                    sw.Close();

                    f_succeeded = true;
                }
            }
            catch (Exception e)
            {                
                //If an error happened during writing, better delete the file
                if (File.Exists(m_loginFile))
                {
                    File.Delete(m_loginFile);
                }                
            }
            
   
        }

        return f_succeeded;
    }
}